import 'dart:async';

import '../core.dart';
import '../model/config.dart';
import 'index.dart';

/// 节流，下一个pipe将接收到一个数组。做了通用化处理，这里可以接受所有类型的log
Function(List<T> msg, Resolve resolve) createThrottlePipe<T>(Core aegis,
    [num? maxLength]) {
  Timer? timer;
  List<T> msgs = [];
  Config config = aegis.config;
  aegis.lifeCycle.on('destroy', null, (ev, context) {
    msgs = [];
  });

  return (List<T> msg, Function resolve) {
    msgs = msgs + msg;
    if (maxLength != null && msgs.length >= maxLength) {
      resolve(msgs.sublist(0, msgs.length));
      msgs = [];
      timer?.cancel();

      return;
    }
    timer?.cancel();
    timer = Timer(Duration(milliseconds: config.delay), () {
      timer = null;
      if (msgs.isNotEmpty) {
        resolve(msgs.sublist(0, msgs.length));
        msgs = [];
      }
    });
  };
}
